package com.nandi.emergencyinspection.ui.activity

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.KeyEvent
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.viewpager.widget.ViewPager
import com.flyco.tablayout.listener.OnTabSelectListener
import com.luck.picture.lib.tools.ToastUtils
import com.nandi.emergencyinspection.R
import com.nandi.emergencyinspection.bean.TaskListBean
import com.nandi.emergencyinspection.mvp.MainContract
import com.nandi.emergencyinspection.mvp.MainPresenter
import com.nandi.emergencyinspection.ui.adapter.ListAdapter
import com.nandi.emergencyinspection.ui.adapter.ViewPagerAdapter
import com.nandi.emergencyinspection.ui.fragment.Fragment1
import com.tbright.ktbaselibrary.extension.isVisiable
import com.tbright.ktbaselibrary.mvp.BaseMvpActivity
import io.rong.imlib.RongIMClient
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.fragment_1.view.*
import kotlinx.android.synthetic.main.header_layout.*
import kotlinx.android.synthetic.main.search_layout.*
import java.util.*
import kotlin.collections.ArrayList

class MainActivity : BaseMvpActivity<MainPresenter>(), MainContract.MainView {
    private var fragments: ArrayList<Fragment>? = null
    private val datas: ArrayList<TaskListBean.RecordsBean?> = ArrayList()
    private var listAdapter: ListAdapter = ListAdapter(datas)
    private val titles: ArrayList<String> = ArrayList()
    var mTitles = arrayOf("未接受", "进行中", "已完成", "已终止")

    private var isExit = false
    override fun getLayoutId(): Int {
        return R.layout.activity_main
    }

    override fun initView(savedInstanceState: Bundle?) {
        left_icon.isVisiable = false
        right_icon.isVisiable = true
        center_txt.text = "应急巡检"
        right_icon.setOnClickListener {
            startActivity(Intent(this, UserInfoActivity::class.java))
        }
        listAdapter.setOnItemClickListener { adapter, view, position ->
            val recordsBean = adapter.data[position] as TaskListBean.RecordsBean
            startActivity(
                Intent(this, TaskInfoActivity::class.java).putExtra(
                    "data",
                    recordsBean
                )
            )
        }
        search_data.apply {
            layoutManager = LinearLayoutManager(this@MainActivity)
            adapter = listAdapter
        }
        listAdapter.setEmptyView(R.layout.emputy_layout)

        search_edit.setOnEditorActionListener(object : TextView.OnEditorActionListener {
            override fun onEditorAction(p0: TextView?, actionId: Int, p2: KeyEvent?): Boolean {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    search_img.isEnabled = true
                    search_img.setImageResource(R.drawable.icon_close)
                    if (p0?.text.toString().trim().isNotEmpty()) {
                        mPresenter?.getList(
                            page = 1,
                            size = 10000,
                            taskName = p0?.text.toString().trim()
                        )
                    } else {
                        ToastUtils.s(this@MainActivity, "请输入要搜索得内容")
                    }
                    return true
                }
                return false

            }

        })

        search_img.setOnClickListener {
            search_edit.setText("")
            search_img.isEnabled = false
            search_img.setImageResource(R.drawable.icon_search)
            search_data.isVisiable = false
            viewpager_ll.isVisiable = true
        }
//        mPresenter?.getImToken()
        fragments = ArrayList()
        mTitles.forEachIndexed { index, s ->
            fragments!!.add(Fragment1.newInstance(index))
        }

        initTab()
    }

    private fun initTab() {
        //添加适配器
        tablayout1.setTabData(mTitles)
        //TabLayout和Viewpager2进行关联
        tablayout1.indicatorCornerRadius = 10F;//设置圆角
        tablayout1.textSelectColor = Color.WHITE;//选中文字颜色
        tablayout1.textUnselectColor = Color.parseColor("#02C8FD")//未选中文字颜色
        tablayout1.indicatorColor = Color.parseColor("#02C8FD")//选中区域颜色
        tablayout1.dividerColor = Color.parseColor("#02C8FD")//设置分割线颜色
//        tablayout1.setIndicatorMargin(1F, 1F, 1F, 1F)
        tablayout1.setOnTabSelectListener(object : OnTabSelectListener {
            override fun onTabSelect(position: Int) {
                v2.currentItem = position
            }

            override fun onTabReselect(position: Int) {
            }

        })
        v2.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {

            }

            override fun onPageSelected(position: Int) {
                tablayout1.currentTab = position;
            }

            override fun onPageScrollStateChanged(state: Int) {
            }

        })

        val myFragmentStateAdapter =
            ViewPagerAdapter(supportFragmentManager, fragments!!)
        v2.adapter = myFragmentStateAdapter
    }

    override fun showResult(result: TaskListBean?) {
        search_data.isVisiable = true
        viewpager_ll.isVisiable = false
        listAdapter.setList(result?.records)
    }

    override fun onBackPressed() {
        super.onBackPressed()
        exitBy2Click()
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if(keyCode == KeyEvent.KEYCODE_BACK)
        {
            exitBy2Click();		//调用双击退出函数
        }
        return false
    }
    /**
     * 再次按下返回键退出
     */

    private fun exitBy2Click() {
        var tExit: Timer? = null
        if (false === isExit) {
            isExit = true // 准备退出
            ToastUtils.s(this, "再按一次退出程序")
            tExit = Timer()
            tExit.schedule(object : TimerTask() {
                override fun run() {
                    isExit = false // 取消退出
                }
            }, 2000) // 如果2秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务
        } else {
            finish()
            RongIMClient.getInstance().logout()
            System.exit(0)
        }
    }


}